package com.ruoyi.web.controller.module.estate;

import java.util.List;
import java.util.Arrays;

import cn.hutool.core.util.StrUtil;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.PageUtils;
import com.ruoyi.system.domain.module.estate.Estate;
import com.ruoyi.system.domain.module.estate.EstateWorkLog;
import com.ruoyi.system.service.module.estate.IEstateService;
import com.ruoyi.system.service.module.estate.IEstateUserService;
import com.ruoyi.system.service.module.estate.IEstateWorkLogService;
import com.ruoyi.system.service.module.property.IPropertyService;
import com.ruoyi.system.service.module.wx.IWxUserService;
import com.ruoyi.system.service.system.ISysDeptService;
import com.ruoyi.system.service.system.ISysUserService;
import lombok.RequiredArgsConstructor;

import javax.swing.text.Document;
import javax.validation.constraints.*;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.validation.annotation.Validated;
import com.ruoyi.common.annotation.RepeatSubmit;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.web.controller.common.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.validate.AddGroup;
import com.ruoyi.common.core.validate.EditGroup;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

/**
 * 工作日志Controller
 *
 * @author ruoyi
 * @date 2024-08-01
 */
@Validated
@Api(value = "工作日志控制器", tags = {"工作日志管理"})
@RequiredArgsConstructor(onConstructor_ = @Autowired)
@RestController
@RequestMapping("/module/estate/log")
public class EstateWorkLogController extends BaseController {

    private final IEstateWorkLogService estateWorkLogService;
	private final IEstateService estateService;
	private final ISysDeptService sysDeptServicel;
	private final ISysUserService sysUserService;
	private final IWxUserService wxUserService;
    /**
     * 查询工作日志列表
     */
    @ApiOperation("查询工作日志列表")
    @PreAuthorize("@ss.hasPermi('module:estateLog:list')")
    @GetMapping("/list")
    public TableDataInfo<EstateWorkLog> list(@Validated EstateWorkLog estateWorkLog) {
		SysUser sysUser = getUser();
        QueryWrapper<EstateWorkLog> qw = new QueryWrapper<>();
		if(sysUser!=null){
			if(sysUser.getUserType() < 2){
			} else if(sysUser.getUserType() == 3){//小区
				qw.eq("estate_id",sysUser.getEstateId());
			} else if (sysUser.getUserType() == 2){
				if (sysUser.getEstateId()!=null){
					qw.eq("estate_id",sysUser.getEstateId());
				}
				if (sysUser.getEstateId()==null && estateWorkLog.getEstateId()==null){
					QueryWrapper qwEstate = new QueryWrapper<>();
					qwEstate.eq("property_id",sysUser.getPropertyId());
					List<Estate> estates = estateService.list(qwEstate);
					for (Estate estate:estates){
						qw.or().eq("estate_id",estate.getId());
					}
				}
			}
		}
		if (estateWorkLog.getEstateId()!=null){
			qw.eq("estate_id",estateWorkLog.getEstateId());
		}
		if (estateWorkLog.getDeptId()!=null){
			qw.eq("dept_id",estateWorkLog.getDeptId());
		}
		if (estateWorkLog.getName()!=null){
			qw.like("name",estateWorkLog.getName());
		}
		if(StrUtil.isNotEmpty(estateWorkLog.getBeginDate())){
			qw.between("create_time",estateWorkLog.getBeginDate() + " 00:00:00",estateWorkLog.getEndDate() + " 23:59:59");
		}
		qw.eq("log_type",0);
		qw.orderByDesc("create_time");
        TableDataInfo<EstateWorkLog> td = PageUtils.buildDataInfo(estateWorkLogService.page(PageUtils.buildPage(),qw));
        List<EstateWorkLog> list = td.getRows();
		if (list.size()>0){
			for (EstateWorkLog log:list){
				if (log.getEstateId()!=null){
					log.setEstateName(estateService.findById(log.getEstateId()).getEstateName());
				}
				if (log.getDeptId()!=null){
					log.setDeptName(sysDeptServicel.getById(log.getDeptId()).getDeptName());
				}
				if (log.getUserId()!=null){
					log.setUserName(wxUserService.findById(log.getUserId()).getNickName());
				}
				if (log.getSysUserId()!=null){
					log.setSysUserName(sysUserService.getById(log.getSysUserId()).getNickName());
				}else {
					log.setSysUserName("未绑定后台账号");
				}
			}
		}
        return td;
    }

    /**
     * 导出工作日志列表
     */
    @ApiOperation("导出工作日志列表")
    @PreAuthorize("@ss.hasPermi('module:estateLog:export')")
    @Log(title = "工作日志", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    public AjaxResult<EstateWorkLog> export(@Validated EstateWorkLog estateWorkLog) {
		SysUser sysUser = getUser();
		QueryWrapper<EstateWorkLog> qw = new QueryWrapper<>();
		if(sysUser!=null){
			if(sysUser.getUserType() < 2){
			} else if(sysUser.getUserType() == 3){//小区
				qw.eq("estate_id",sysUser.getEstateId());
			} else if (sysUser.getUserType() == 2){
				if (sysUser.getEstateId()!=null){
					qw.eq("estate_id",sysUser.getEstateId());
				}
				if (sysUser.getEstateId()==null && estateWorkLog.getEstateId()==null){
					QueryWrapper qwEstate = new QueryWrapper<>();
					qwEstate.eq("property_id",sysUser.getPropertyId());
					List<Estate> estates = estateService.list(qwEstate);
					for (Estate estate:estates){
						qw.or().eq("estate_id",estate.getId());
					}
				}
			}
		}
		if (estateWorkLog.getEstateId()!=null){
			qw.eq("estate_id",estateWorkLog.getEstateId());
		}
		if (estateWorkLog.getDeptId()!=null){
			qw.eq("dept_id",estateWorkLog.getDeptId());
		}
		if (estateWorkLog.getName()!=null){
			qw.like("name",estateWorkLog.getName());
		}
		if(StrUtil.isNotEmpty(estateWorkLog.getBeginDate())){
			qw.between("create_time",estateWorkLog.getBeginDate() + " 00:00:00",estateWorkLog.getEndDate() + " 23:59:59");
		}
		qw.eq("log_type",0);
		qw.orderByDesc("create_time");
		List<EstateWorkLog> list = estateWorkLogService.list(qw);
		if (list.size()>0){
			for (EstateWorkLog log:list){
				if (log.getEstateId()!=null){
					log.setEstateName(estateService.findById(log.getEstateId()).getEstateName());
				}
				if (log.getDeptId()!=null){
					log.setDeptName(sysDeptServicel.getById(log.getDeptId()).getDeptName());
				}
				if (log.getUserId()!=null){
					log.setUserName(wxUserService.findById(log.getUserId()).getNickName());
				}
				if (log.getContent()!=null){
					String regex = "<p>";
					String regex1 = "</p>";
					String regex3 = "<br>";
					String regex4 = "</br>";
					String text = log.getContent().replaceAll(regex, "");
					text = text.replaceAll(regex1, "");
					text = text.replaceAll(regex3, "");
					text = text.replaceAll(regex4, "");
					log.setContentText(text);
				}
				if (log.getCreateTime()!=null){
					log.setCreateTimeStr(DateUtils.getTime(log.getCreateTime()));
				}
				if (log.getSysUserId()!=null){
					log.setSysUserName(sysUserService.getById(log.getSysUserId()).getNickName());
				}else {
					log.setSysUserName("未绑定后台账号");
				}
			}
		}
        ExcelUtil<EstateWorkLog> util = new ExcelUtil<EstateWorkLog>(EstateWorkLog.class);
        return util.exportExcel(list, "工作日志");
    }

    /**
     * 获取工作日志详细信息
     */
    @ApiOperation("获取工作日志详细信息")
    @PreAuthorize("@ss.hasPermi('module:estateLog:query')")
    @GetMapping("/{id}")
    public AjaxResult<EstateWorkLog> getInfo(@NotNull(message = "主键不能为空") @PathVariable("id") Long id) {
        EstateWorkLog estateWorkLog = estateWorkLogService.getById(id);
        return AjaxResult.success(estateWorkLog);
    }

    /**
     * 新增工作日志
     */
    @ApiOperation("新增工作日志")
    @PreAuthorize("@ss.hasPermi('module:estateLog:add')")
    @Log(title = "工作日志", businessType = BusinessType.INSERT)
    @RepeatSubmit
    @PostMapping()
    public AjaxResult<Void> add(@Validated(AddGroup.class) @RequestBody EstateWorkLog estateWorkLog) {
        return toAjax(estateWorkLogService.save(estateWorkLog) ? 1 : 0);
    }

    /**
     * 修改工作日志
     */
    @ApiOperation("修改工作日志")
    @PreAuthorize("@ss.hasPermi('module:estateLog:edit')")
    @Log(title = "工作日志", businessType = BusinessType.UPDATE)
    @RepeatSubmit
    @PutMapping()
    public AjaxResult<Void> edit(@Validated(EditGroup.class) @RequestBody EstateWorkLog estateWorkLog) {
        return toAjax(estateWorkLogService.updateById(estateWorkLog) ? 1 : 0);
    }

    /**
     * 删除工作日志
     */
    @ApiOperation("删除工作日志")
    @PreAuthorize("@ss.hasPermi('module:estateLog:remove')")
    @Log(title = "工作日志" , businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult<Void> remove(@NotEmpty(message = "主键不能为空")  @PathVariable Long[] ids) {
        return toAjax(estateWorkLogService.removeByIds(Arrays.asList(ids)) ? 1 : 0);
    }
}
